<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let obj = {
            name: 'wsh',
            age: 18
        }
        // observer观测类
        export class Observer{
            constructor(value) {
                this.value = value
                if (value instanceof Array) {
                    // 数组逻辑
                } else {
                    // 对象逻辑
                    this.walk(value)
                }
            }
            walk(obj) {
                const keys = Object.keys(obj)
                for (let index = 0; index < keys.length; index++) {
                    defineReactive(obj, keys[index])                       
                }
            }
        }
        // 此处多定义一个参数是为了减少在函数内声明一个变量
        function defineReactive(obj, key, val) {
            if(arguments.length === 2) {
                val = obj[key]
            }
            // 递归
            if (typeof val === 'object') {
                new Observer(val)
            }
            Object.defineProperty(obj, key, {
                get() {
                    return val
                },
                set(newValue) {
                    // 数据没有发生变化则直接返回
                    if (val === newValue) {
                        return 
                    }
                    val = newValue
                }
            })
        }
    </script>
</body>
</html>